package algo.queue.impl;

import javafx.util.Pair;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/4/29 17:04
 * @Version 1.0
 */
public class QueueLevelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;

        // 我们使用LinkedList来做为我们的先入先出的队列
        LoopQueue<Pair<TreeNode, Integer>> queue = new LoopQueue<>();
        queue.enqueue(new Pair<TreeNode, Integer>(root, 0));

        while(!queue.isEmpty()){

            Pair<TreeNode, Integer> front = queue.dequeue();
            TreeNode node = front.getKey();
            int level = front.getValue();

            if(level == res.size())
                res.add(new ArrayList<Integer>());
            assert level < res.size();

            res.get(level).add(node.val);
            if(node.left != null)
                queue.enqueue(new Pair<>(node.left, level + 1));
            if(node.right != null)
                queue.enqueue(new Pair<>(node.right, level + 1));
        }

        return res;
    }

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

}
